﻿using NLog;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using corel = Corel.Interop.VGCore;

namespace HyperplaneTech.CdrPlugin {
    public partial class MyCdrCloudPlugin : UserControl
    {
        private corel.Application corelApp;
        private Styles.StylesController stylesController;

        /// <summary>
        /// 日志记录器
        /// </summary>
        private static readonly Logger log = NLog.LogManager.GetCurrentClassLogger();

        public MyCdrCloudPlugin(object app)
        {
            InitializeComponent();
            try {
                this.corelApp = app as corel.Application;
                AppManager.cdrApp = this.corelApp;
                stylesController = new Styles.StylesController(this.Resources, this.corelApp);
                // 初始化日志
                InitLogger();
                // 初始化异常处理器
                //InitExceptionHandler();
                // 开启监听
                string settingFile = AppUtil.GetAppSettingFilePath();
                if (File.Exists(settingFile)) {
                    // 如果文件夹存在则开始监听
                    string path = File.ReadAllText(settingFile);
                    if (!Directory.Exists(path)) {
                        return;
                    }
                    // 文件夹存在，开始监听
                    AppManager.StartFileWatch(path);
                }
            } catch (Exception e) {
                log.Error("初始化插件异常：{}", e.Message);
                MessageBox.Show("初始化插件异常：" + e.Message);
            }
            btn_Command.MouseEnter += (s, e) => {
                Image btn = (Image)e.Source;
                btn.Opacity = 0.5;
            };
            btn_Command.MouseLeave += (s, e) => {
                Image btn = (Image)e.Source;
                btn.Opacity = 1;
            };
            btn_Command.MouseDown += (s, e) => {
                Image btn = (Image)e.Source;
                btn.Opacity = 0.25;
            };
            btn_Command.MouseLeftButtonUp += (s, e) => {
                try {
                    log.Error("开始加载窗体");
                    FormUtil.ShowForm(new FrmMain(), (IntPtr)AppManager.cdrApp.AppWindow.Handle);
                } catch (Exception ex) {
                    log.Error("加载窗体异常：{}", ex.Message);
                }
            };
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            stylesController.LoadThemeFromPreference();
        }

        /// <summary>
        /// 初始化日志
        /// </summary>
        private static void InitLogger() {
            try {
                log.Info("开始初始化日志......");
                // 初始化日志路径
                string fileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                string logFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ObjectSizeExtractor";
                string infoLogFileName = logFolder + "\\运行日志.log";
                // 如果文件存在则将其自动删除
                if (File.Exists(infoLogFileName)) {
                    try {
                        File.Delete(infoLogFileName);
                    } catch (Exception ex) {
                        // 忽略异常
                    }
                }
                // 配置NLog
                LogManager.Setup().LoadConfiguration(builder => {
                    builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToFile(fileName: infoLogFileName);
                    builder.ForLogger().FilterMinLevel(LogLevel.Error).WriteToFile(fileName: infoLogFileName);
                });
                log.Info("初始化日志成功");
            } catch (Exception ex) {
                MessageBox.Show("初始化日志发生异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 初始化异常处理器
        /// </summary>
        private void InitExceptionHandler() {
            try {
                this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
                //AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            } catch (Exception ex) {
                log.Error("初始化异常处理器异常：{}", ex.Message);
            }
        }

        /// <summary>
        /// 处理接收Dispatcher未处理异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) {
            try {
                // 这里只打印日志，不弹出消息，减少对用户的干扰
                e.Handled = true;
                log.Error("接收到 Dispatcher 未处理异常：{}" + e.Exception.Message);
            } catch (Exception ex) {
                log.Error("处理接收Dispatcher未处理异常：{}", ex.Message);
            }
        }

    }
}
